import {
  LogoutOutlined,
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Spin, Button, Modal } from 'antd';
import { createStyles } from 'antd-style';
import React from 'react';
import { logout } from '@/pages/user/login/service'

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.name}</span>;
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
  };
});

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({
  menu,
  children,
}) => {
  /**
   * 退出登录
   */
  const loginOut = async () => {
    await logout();
    // 删除 localStorage 中的 token
    localStorage.removeItem('token');
    // 跳转到登录页面
    history.replace('/user/login');
  };
  const { styles } = useStyles();

  const { initialState, setInitialState } = useModel('@@initialState');

  /**
   * 处理退出登录确认
   */
  const handleLogout = () => {
    Modal.confirm({
      title: '退出登录',
      content: '确定要退出登录吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        loginOut();
      },
    });
  };

  const loading = (
    <span className={styles.action}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
      {children}
      <Button
        type="primary"
        danger
        size="small"
        icon={<LogoutOutlined />}
        onClick={handleLogout}
      >
        退出登录
      </Button>
    </div>
  );
};
